import React, {Component} from 'react'
import {Card, InputItem, Picker, List, Toast, Modal, Button} from 'antd-mobile';
import baseFetch from "../../utils/baseFetch";
import { createForm } from 'rc-form';
import {saveUser, getUser} from "../../utils";
import './index.less'
import ResultPage from "../resultPage";
const alert = Modal.alert;

class SearchUser extends Component{
	constructor(props){
		super(props);
		this.state={
			village:[], // 小区
			build:[], //单元号
			door:[],
			lastInRecord:null,
			lastOutRecord:null,
			ishow:false,
			disabled:false,
			user:[],
			type:''
		}
	}

	componentDidMount() {
		this.getVillage()
	}

	getVillage(){
		const {setFieldsValue} = this.props.form;
		baseFetch.get('http://121.229.50.212:8081/noauth/getQuartersTree').then(res => {
			if (res.data){
				let villageData = this.hadelData(res.data);
				this.setState({
					village:villageData,
					ishow:false
				}, () => {
					if (getUser().quarters){
						setFieldsValue({quarters:[getUser().quarters]});
						this.getBuild(getUser().quarters)
					}
				})
			}
		})
	}

	hadelData(data){
		let result =[]
		let loop = (data) => {
			data.forEach(d=>{
				if(d.children.length == 0) {
					result.push({
						value:d.id,
						label:d.title
					})
				} else {
					loop(d.children);
				}
			})
		};
		loop(data)
		return result
	}

	// 获取单元号
	getBuild(id){
		baseFetch.get(`http://121.229.50.212:8081/noauth/getBuildNo/${id}`).then(res => {
			if (res.data){
				let newData = res.data.map(item => {
					return{
						value:item,
						label:item
					}
				});
				this.setState({
					build:newData,
					ishow:false
				})
			}
		})
	}

	getDoor(id){
		const {getFieldValue} = this.props.form
		let quarters = getFieldValue('quarters')[0];
		baseFetch.get(`http://121.229.50.212:8081/noauth/getDoorNo/${quarters}/${id}`).then(res => {
			if (res.data){
				let newData = res.data.map(item => {
					return{
						value:item,
						label:item
					}
				});
				this.setState({
					door:newData,
					ishow:false
				})
			}

		})
	}
	Selectvillage(value){
		const {resetFields, setFieldsValue} = this.props.form;
		setFieldsValue({buildNo:value})
		resetFields(['doorNo']);
		this.getDoor(value[0])
	}
	SelectData(value){
		if (!getUser().quarters){
			saveUser(value[0])
		}
		const {setFieldsValue, resetFields} = this.props.form;
		setFieldsValue({quarters:value});
		resetFields(['buildNo']);
		resetFields(['doorNo']);
		resetFields(['idCard']);
		this.getBuild(value[0])
	}
	selectDoor(value){
		const {setFieldsValue, resetFields} = this.props.form;
		setFieldsValue({doorNo	:value});
		resetFields(['idCard']);
		this.getUser(value[0])
	}

	// 查询结果
	changResult(idCard) {
		const {getFieldValue} = this.props.form;
		let quarters = getFieldValue('quarters')[0];
		let build = getFieldValue('buildNo')[0];
		let doorNo = getFieldValue('doorNo')[0];
		if (!quarters) return Toast.fail('缺少小区');
		if (!build) return Toast.fail('缺少单元号');
		baseFetch.get(`http://121.229.50.212:8081/noauth/crossRecord/checkOutRight/${quarters}/${build}/${doorNo}/${idCard}`).then(res => {
			if (res.type === 'success') {
				const {data} =res
				this.setState({
					outOrInData:{
						allow:data.allow,
						...data.crossTimesRule
					},
					lastInRecord:data.lastInRecord,
					lastOutRecord:data.lastOutRecord,
					ishow:true,
				})
			} else {
				Toast.fail(res.message);
				this.setState({
					outOrInData:{},
					lastInRecord:null,
					lastOutRecord:null,
					ishow:false
				})
			}
		})
	}
	chanegResultUserData () {
		const {getFieldValue} = this.props.form;
		let quarters = getFieldValue('quarters')[0];
		let build = getFieldValue('buildNo')[0];
		let doorNo = getFieldValue('doorNo')[0];
		const idCard = getFieldValue('isCard')[0];
		if (!quarters) return Toast.fail('缺少小区');
		if (!build) return Toast.fail('缺少单元号');
		if (!idCard) return Toast.fail('缺少姓名');
		baseFetch.get(`http://121.229.50.212:8081/noauth/crossRecord/checkOutRight/${quarters}/${build}/${doorNo}/${idCard}`).then(res => {
			if (res.type === 'success') {
				const {data} =res
				this.setState({
					outOrInData:{
						allow:data.allow,
						...data.crossTimesRule
					},
					lastInRecord:data.lastInRecord,
					lastOutRecord:data.lastOutRecord
				})
			} else {
				Toast.fail(res.message);
				this.setState({
					outOrInData:{},
					lastInRecord:null,
					lastOutRecord:null
				})
			}
		})
	}

	InOrOut = (type) => {
		const {storage} = this.state;
		this.props.form.validateFields((error, value) => {
			if (!error){
				let data = {
					doorId:value.doorNo[0],
					idCard:value.idCard,
					buildNo:value.buildNo[0],
					inOut:type,
					quarters:value.quarters[0],
				};
				baseFetch.post('http://121.229.50.212:8081/noauth/crossRecordByStaff/save', data).then(res => {
					if (res.type === 'success') {
						this.chanegResultUserData()
						this.setState({
							disabled:true,
							type: type
						})
					} else {
						Toast.fail(res.message);
						this.setState({
							ishow:false
						})
					}
				})
			} else {
				let errArr = [];
				for (let key in error) {
					errArr.push(error[key].errors[0].message)
				}
				const [first] = errArr.reverse();
				Toast.fail(first)
			}
		})
	};

	selectUser(value){
		const {setFieldsValue} = this.props.form;
		setFieldsValue({isCard	:value});
		this.changResult(value[0])
	}
	getUser(door){
		const {getFieldValue} = this.props.form;
		let quarters = getFieldValue('quarters')[0];
		let build = getFieldValue('buildNo')[0];
		if (!quarters) return Toast.fail('缺少小区');
		if (!build) return Toast.fail('缺少单元号');
		baseFetch.get(`http://121.229.50.212:8081/noauth/searchFamilyResidentByStaff/${quarters}/${build}/${door}`).then(res => {
			if (res.type === 'success') {
				const {data} =res;
				let newData = data.map(item => {
					return{
						value:item.idCard,
						label:item.name
					}
				});
				this.setState({
					user:newData,
					ishow:false
				})
			} else {
				Toast.fail(res.message);
				this.setState({
					user:[],
					ishow:false
				})
			}
		})
	}

	render() {
		const { getFieldProps, getFieldValue } = this.props.form;
		const {village, build, door, outOrInData, lastInRecord, lastOutRecord, ishow, user} = this.state;
		return(
			<div>
				{
					!this.state.disabled	?
						<div className="flex-container">
							<List renderHeader={() => '小区进出安全检查记录系统'} className="list">
								<Picker
									data={village}
									cols={1}
									{...getFieldProps('quarters',{
										rules: [
											{
												required: true,
												message: '请选择小区'
											}
										],
									})}
									onChange={(val) => this.SelectData(val)}
								>
									<List.Item arrow="horizontal">
										小区
									</List.Item>

								</Picker>
								<Picker
									data={build}
									cols={1}
									{...getFieldProps('buildNo',{
										rules: [
											{
												required: true,
												message: '请选择单元号'
											}
										],
									})}
									onChange={(val) => this.Selectvillage(val)}
								>
									<List.Item arrow="horizontal">
										单元号
									</List.Item>
								</Picker>
								<Picker
									data={door}
									cols={1}
									{...getFieldProps('doorNo',{
										rules: [
											{
												required: true,
												message: '请选择门牌号'
											}
										],
									})}
									onChange={(val) => this.selectDoor(val)}
								>
									<List.Item arrow="horizontal">
										门牌号
									</List.Item>
								</Picker>
								<Picker
									data={user}
									cols={1}
									{...getFieldProps('isCard',{
										rules: [
											{
												required: true,
												message: '请选姓名'
											}
										],
									})}
									onChange={(val) => this.selectUser(val)}
								>
									<List.Item arrow="horizontal">
										姓名
									</List.Item>
								</Picker>
							</List>
							{
								ishow &&
								<Card.Body>
									<div>
										<h2>进出记录</h2>
										<div className={'userinfo'}>
											<label>最后一次进记录</label>
											{
												lastInRecord ? <ul className={'ul'}>
													{
														lastInRecord.doorIdText && <li className={'li'}><label>大门名称:</label> <span>{lastInRecord.doorIdText}</span></li>
													}
													<li className={'li'}><label>身份证:</label> <span>{lastInRecord.idCard.replace(/(\w{10})\w*(\w{2})/, '$1******$2') || ''}</span></li>
													<li className={'li'}><label>时间:</label> <span>{lastInRecord.createTime || ''}</span></li>
												</ul> : <ul className={'ul'}> <li className={'li'}>暂无数据</li> </ul>
											}

										</div>

										<div className={'userinfo'}>
											<label>最后一次出记录</label>
											{
												lastOutRecord ? <ul className={'ul'}>
													{
														lastOutRecord.doorIdText && <li className={'li'}><label>大门名称:</label> <span>{lastOutRecord.doorIdText}</span></li>
													}

													<li className={'li'}><label>身份证:</label> <span>{lastOutRecord.idCard.replace(/(\w{10})\w*(\w{2})/, '$1******$2') || ''}</span></li>
													<li className={'li'}><label>时间:</label> <span>{lastOutRecord.createTime || ''}</span></li>
												</ul> : <ul className={'ul'}> <li className={'li'}>暂无数据</li> </ul>
											}

										</div>
										<div className={'divider'}></div>
										<h2>进出规则</h2>
										<div className={'userinfo error'}>
											<label>描述</label> <span>{outOrInData.describe}</span>
										</div>
										{
											outOrInData.isolation && <div className={'userinfo error'}>
												<label>隔离剩余天数</label> <span>{outOrInData.isolation}天</span>
											</div>
										}
										{
											!outOrInData.isolation && <div className={'userinfo error'}>
												<label>次数</label> <span>每{outOrInData.perUnit}天{outOrInData.perUnitTimes}次</span>
											</div>
										}
										<div className={'divider'}></div>
										{
											outOrInData.allow && <div className={'button'}>
												<Button
													type="primary"
													onClick={() =>
														alert( '进' , '确定?', [
															{ text: '取消', onPress: () => console.log('cancel') },
															{ text: '确认', onPress: () => this.InOrOut('in')},
														])
													}
													disabled={this.state.disabled}
												>
													<div className={'btn'}>进</div>
												</Button>
												<Button
													type="primary"
													onClick={() =>
														alert( '出' , '确定?', [
															{ text: '取消', onPress: () => console.log('cancel') },
															{ text: '确认', onPress: () => this.InOrOut('out')},
														])
													}
													disabled={this.state.disabled}
												>
													<div className={'btn'}>出</div>
												</Button>
											</div>
										}
										{
											!outOrInData.allow && <h2 className={'error text_center'}>当前不可出入</h2>
										}
									</div>
								</Card.Body>
							}
						</div>
						:
						<ResultPage
							{...this.props}
							data={this.state.type === 'in' ? lastInRecord : lastOutRecord}
							type={this.state.type}
						/>
				}


			</div>

		)
	}

}

export default createForm()(SearchUser)
